﻿using System;
using System.Linq;
using System.Net.Sockets;

namespace WebTranslator {
	//Client - Master Server protocol - Client version
	public class CMSProtocolC : ClientProtocol {
		string login = "";
		string hostIp;
		public bool Connect(string ip) {
			if (client != null && client.Client != null && client.Connected) {
				Send("quit");
				Disconnect();
			}
			hostIp = ip;
			try {
				client = new TcpClient(ip, StartingApplicationPorts.MainServerToClients);
				SetSockets(client.Client);
				HandShake();
				return true;
			} catch (Exception) {
				return false;
			}
		}
		private void HandShake() {
			string s = "czesc " + login;
			Send(s);
			s = Receive();
			if (s.StartsWith("czesc")) {
				s = s.Split(' ')[1];
				Disconnect();
				client = new TcpClient(hostIp, int.Parse(s));
				SetSockets(client.Client);
				s = "OK";
				Send(s);
				Receive();
			}
		}

		public string Login(string login, string password) {
			Send("login " + login + " " + password);
			this.login = login;
			return Receive();
		}

		public void ConnectToLanguageServer() {
			Send("serwerjezykowy");
			string msg = Receive();
			TcpClient oldClient = client;
			if (msg.Contains(':')) {
				string[] napisy = msg.Split(':');
				Disconnect();
				client = new TcpClient(napisy[0], int.Parse(napisy[1]));
				SetSockets(client.Client);
				hostIp = napisy[0];
				HandShake();
			} else {
				client = oldClient;
				SetSockets(client.Client);
				throw new ServerUnavailableException(msg);
			}
		}

		public string IlePunktow() {
			Send("ilemampkt " + login);
			return Receive();
		}

		public void MojeTeksty(out string[] teksty) {
			Send("mojeteksty");
			string msg = Receive();
			int ile = int.Parse(msg);
			teksty = new string[ile];
			for (int i = 0; i < ile; ++i) {
				teksty[i] = Receive();
			}
		}

		public void SzczegolyTekstu(string title, out string source, out string translation) {
			Send("szczegoly " + title);
			source = Receive();
			translation = Receive();
		}
	}
	public class ServerUnavailableException : Exception {
		public ServerUnavailableException(string msg)
			: base(msg) {
		}
	}
}
